package com.apache.rpc.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.database.model.TaskEntity;
import com.apache.rpc.manager.DynamicDatabaseManager;
import com.apache.task.api.ScheduledExecutor;
import com.apache.tools.ClassToolsUtil;
import com.apache.tools.StrUtil;

import java.util.List;

/**
 * description:
 *
 * @author dyh 创建时间：2018年10月01日
 */
public class TaskTimerActionPluginImpl implements PluginConnector {

    private DynamicDatabaseManager taskTimerManager;
    private CacheManager cache;

    @Override
    public Object execute(ParamsVo param) throws Exception {
        String method = String.valueOf(param.getParams("method"));
        ResultEntity entity = new ResultEntity();
        entity.setResult("true");
        if ("loadCache".equalsIgnoreCase(method)) {
            loadCache(entity, param);
        } else if ("list".equalsIgnoreCase(method)) {
            list(entity, param);
        } else if ("save".equalsIgnoreCase(method)) {
            save(entity, param);
        } else if ("info".equalsIgnoreCase(method)) {
            info(entity, param);
        } else if("del".equalsIgnoreCase(method)){
            del(entity,param);
        }else if("startOrStop".equalsIgnoreCase(method)){
            startOrStop(entity,param);
        }
        param = null;
        return entity;
    }

    private void startOrStop(ResultEntity entity,ParamsVo param){
        String taskKey = param.getParamsToStr("taskKey");
        Object obj = ScheduledExecutor.newInstance().getCache().getCacheObjectByKey(taskKey);
        if(null == obj){
            entity.setMessage("操作失败");
        }
        String openStatus = StrUtil.doNull(param.getParamsToStr("openStatus"),"false");
        TaskEntity item = (TaskEntity)obj;
        item.setOpenStart(Boolean.valueOf(openStatus));
        ScheduledExecutor.newInstance().getCache().createCacheObject(taskKey,item);
    }

    private void del(ResultEntity entity,ParamsVo param){
        String taskKey = param.getParamsToStr("taskKey");
        String sysName = param.getParamsToStr("sysName");
        String serverIp = param.getParamsToStr("serverIp");
        ParamsVo vo = new ParamsVo();
        vo.setInfoId(taskKey);
        Object obj = taskTimerManager.getInfoById(vo);
        if(null == obj){
            entity.setMessage("没有待删除的信息，请您确认操作");
        }
        TaskEntity item = (TaskEntity)obj;
        if(!item.getSysName().equals(sysName) || !item.getServerIp().equals(serverIp)){
            entity.setMessage("您无权删除此信息，请您确认操作");
        }
        boolean mark = taskTimerManager.deleteInfo(vo);
        if(mark){
            entity.setEntity("删除成功");
            entity.setMessage("删除成功");
        }else{
            entity.setMessage("信息删除失败");
        }
    }

    private void info(ResultEntity entity, ParamsVo param) {
        String taskKey = String.valueOf(param.getParams("taskKey"));
        ParamsVo vo = new ParamsVo();
        vo.setInfoId(taskKey);
        Object obj = taskTimerManager.getInfoById(vo);
        entity.setEntity(obj);
        entity.setMessage("查询成功");
    }

    private void loadCache(ResultEntity entity, ParamsVo param) {
        ParamsVo vo = new ParamsVo();
        vo.setKey("initCache");
        vo.setParams("sysName",param.getParamsToStr("sysName"));
        taskTimerManager.execute(vo);
        entity.setEntity("true");
        entity.setMessage("操作成功！");
    }

    private void list(ResultEntity entity, ParamsVo param) {
        ParamsVo vo = new ParamsVo();
        String rows = StrUtil.doNull(String.valueOf(param.getParams("pageSize")),
                String.valueOf(param.getParams("rows")));
        String page = StrUtil.doNull(String.valueOf(param.getParams("pageIndex")),
                String.valueOf(param.getParams("page")));
        vo.setMethodKey("ForIds");
        vo.setParams(param.getParams());
        if(Validator.isNotNull(rows)){
            vo.setParams("pageIndex", page);
            vo.setParams("pageSize", rows);
            Page pageList = taskTimerManager.getPageInfo(vo);
            if(!Validator.isEmpty(pageList.getPageObjects())) {
                List list = getCache().getObjects(pageList.getPageObjects());
                pageList.setPageObjects(list);
            }
            entity.setEntity(pageList);
        }else{
            List list = taskTimerManager.getList(vo);
            if(!Validator.isEmpty(list)){
                entity.setEntity(getCache().getObjects(list));
            }
        }
        entity.setMessage("查询成功");
    }

    private void save(ResultEntity entity, ParamsVo vo) {
        ParamsVo<TaskEntity> param = new ParamsVo<>();
        TaskEntity item = new TaskEntity();
        item = (TaskEntity) ClassToolsUtil.getInstance().convert2Bean(vo.getParams(), item);
        if (Validator.isNull(item.getClassName())) {
            entity.setMessage("任务名称不能空");
            return;
        } else {
            param.setObj(item);
            if(Validator.isNull(item.getTaskKey())){
                String id = taskTimerManager.saveInfo(param);
                if (Validator.isNull(id)) {
                    entity.setMessage("保存失败");
                } else {
                    entity.setEntity(id);
                    entity.setMessage("保存成功");
                }
            }else{
                boolean mark = taskTimerManager.editInfo(param);
                if (mark) {
                    entity.setEntity(item.getTaskKey());
                    entity.setMessage("修改成功");
                } else {
                    entity.setMessage("修改失败");
                }
            }
        }
    }


    public void setTaskTimerManager(DynamicDatabaseManager taskTimerManager) {
        this.taskTimerManager = taskTimerManager;
    }

    private CacheManager getCache(){
        if(null==cache){
            cache = LoadCacheFactory.getInstance().getCacheManager("task_timer_map");
        }
        return cache;
    }
}
